<template>
  <!--APP初始化配置-->
  <div class="content_panel project_modules">
    <div class="content_panel_top">
      <h3 class="panel_title">
        <span>{{$t('common.appInitialization')}}</span>
      </h3>
      <el-form ref="form" :model="form" :rules="rules" :inline="false" class="module_form">
        <el-row>
          <el-col :span="8">
            <!-- APP包名 -->
            <el-form-item prop="appItemInfo">
              <el-select v-model="form.appItemInfo" :placeholder="$t('system.appName')" style="width:100%;" @change="updatePageInfo">
                <el-option v-for="item in appList" :key="item.id" :value="JSON.stringify(item)" :label="`${item.packageName}[${item.name}]`"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="module_content">
      <div class="content_panel project_modules">
        <div class="table_list">
          <table class="gridtable">
            <tr>
              <th>{{ $t('common.configurationItem') }}</th>
              <th>{{ $t('common.setAndOperation') }}</th>
              <th>{{ $t('common.contentOverview') }}</th>
              <th>{{ $t('common.updateTime') }}</th>
            </tr>
            <tr>
              <td>{{ $t('common.domainName') }}</td>
              <td>
                <el-button @click="showSettingsDialog('primaryDomainUrl', 'edit')" type="text">{{ $t('finance.edit') }}</el-button>
                <el-button @click="showSettingsDialog('primaryDomainUrl', 'check')" type="text">{{ $t('common.check') }}</el-button>
              </td>
              <td>{{ packagingInfo.primaryDomainUrl | substrText(50)}}</td>
              <td>{{ packagingInfo.createTime }}</td>
            </tr>
            <tr>
              <td>{{ $t('common.codeNaseAddress') }}</td>
              <td>
                <el-button @click="showSettingsDialog('gitUrl', 'edit')" type="text">{{ $t('finance.edit') }}</el-button>
                <el-button @click="showSettingsDialog('gitUrl', 'check')" type="text">{{ $t('common.check') }}</el-button>
              </td>
              <td>{{ packagingInfo.gitUrl }}</td>
              <td>{{ packagingInfo.createTime }}</td>
            </tr>
            <tr>
              <td>{{ $t('common.offlinePackageCodeBranch') }}</td>
              <td>
                <el-button @click="showSettingsDialog('gitBranch', 'edit')" type="text">{{ $t('finance.edit') }}</el-button>
                <el-button @click="showSettingsDialog('gitBranch', 'check')" type="text">{{ $t('common.check') }}</el-button>
              </td>
              <td>{{ packagingInfo.gitBranch }}</td>
              <td>{{ packagingInfo.createTime }}</td>
            </tr>
            <tr>
              <td>{{ $t('common.autoSendSms') }}</td>
              <td>
                <el-button @click="initSmsTemplateForAppName()" type="text">{{ $t('common.oneClickInitialization') }}</el-button>
              </td>
              <td></td>
              <td>{{initialUpTimes.smsUpdateTime}}</td>
            </tr>
            <tr>
              <td>{{ $t('common.colPhaseAndSms') }}</td>
              <td>
                <el-button @click="initConfigAndTemplateForAppName()" type="text">{{ $t('common.oneClickInitialization') }}</el-button>
              </td>
              <td></td>
              <td>{{initialUpTimes.collectionUpdateTime | formatDate('yyyy-MM-dd hh:mm:ss')}}</td>
            </tr>
          </table>
        </div>
      </div>
    </div>

    <!--编辑弹框-->
    <el-dialog :visible.sync="settingsDialog.settingsDialogShow" width="450px" :title="isEditDialog ? $t('finance.edit'): $t('common.check')">
      <el-form :model="settingsDialog.form" ref="settingsDialog.form" :rules="settingsDialog.rules" label-width="120px">
        <el-form-item v-if="settingsDialog.key === 'primaryDomainUrl'" :label="$t('common.domainName') + ' : '">
          <!--主域名-->
          <el-input v-if="isEditDialog" v-model="settingsDialog.form.primaryDomainUrl" type="text" :placeholder="$t('verify.plsInput')"></el-input>
          <span v-else>{{settingsDialog.form.primaryDomainUrl}}</span>
        </el-form-item>
        <el-form-item v-if="settingsDialog.key === 'gitUrl'" :label="$t('common.codeNaseAddress') + ' : '">
          <!--代码库地址-->
          <el-input v-if="isEditDialog" v-model="settingsDialog.form.gitUrl" type="text" :disabled="settingsDialog.type ==='check'" :placeholder="$t('verify.plsInput')"></el-input>
          <span v-else>{{ settingsDialog.form.gitUrl }}</span>
        </el-form-item>
        <el-form-item v-if="settingsDialog.key === 'gitBranch'" :label="$t('common.offlinePackageCodeBranch') + ' : '">
          <!--离线包代码分支-->
          <el-input v-if="isEditDialog" v-model="settingsDialog.form.gitBranch" type="text" :disabled="settingsDialog.type ==='check'" :placeholder="$t('verify.plsInput')"></el-input>
          <span v-else>{{ settingsDialog.form.gitBranch }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="submitEdit" type="primary">{{$t('common.confirmOk')}}</el-button>
        <el-button @click="settingsDialog.settingsDialogShow = false" type="default">{{$t('common.cancel')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  let that = null;
  export default {
    name: 'systemAuthority-appInitialConfiguration',
    components: {},
    data() {
      return {
        packagingInfo: {
          primaryDomainUrl: '',
          gitUrl: '',
          gitBranch: '',
          createTime: ''
        },
        initialUpTimes: {
          smsUpdateTime: '',
          collectionUpdateTime: ''
        },
        form: {
          appItemInfo: ''
        },
        appList: [],
        formLabelWidth:
          this.$i18n.locale === 'zhCN' ? '145px' : '235px',
        rules: {},
        user: this.$storage.get('user'),
        settingsDialog: {
          settingsDialogShow: false,
          type: '',
          key: '',
          form: {
            primaryDomainUrl: '',
            gitUrl: '',
            gitBranch: ''
          },
          rules: {}
        }
      };
    },
    computed: {
      isEditDialog() {
        return this.settingsDialog.type === 'edit'
      }
    },
    methods: {
      updatePageInfo() {
        this.getPackagingInfo();
        this.querySmsUpdateTime();
        this.queryCollectionUpdateTime();
      },
      // 获取app配置数据
      getPackagingInfo() {
        const { name, domain, company, packageName } = JSON.parse(
          this.form.appItemInfo
        );
        const params = {
          appName: name,
          domain,
          company,
          appPackage: packageName
        };
        this.$api.systemManage.getapppackconfig(params).then(res => {
          const { status, data, error } = res;
          if ('1' === status && '00000000' === error && data) {
            this.packagingInfo = data;
          } else {
            this.packagingInfo = {
              primaryDomainUrl: '',
              gitUrl: '',
              gitBranch: ''
            };
          }
        });
      },
      getAppList() {
        const params = {
          username: '',
          id: '',
          cpId: '',
          status: 1,
          pageNum: 1,
          pageSize: 10000
        };
        this.$api.systemManage.getUserCompanyList(params).then(res => {
          const { status, data, error } = res;
          if ('1' === status && error === '00000000') {
            data.userList.forEach(item => {
              if (item.apps instanceof Array) {
                item.apps.forEach(subItem => {
                  subItem.domain = item.username;
                  subItem.company = item.companyName;
                });
                this.appList = [...this.appList, ...item.apps];
              }
            });
            if (this.appList.length > 0) {
              this.form.appItemInfo = JSON.stringify(this.appList[0]);
            }
            this.updatePageInfo();
          }
        });
      },
      showSettingsDialog(key, type) {
        this.settingsDialog.type = type;
        this.settingsDialog.key = key;
        this.settingsDialog.form = JSON.parse(JSON.stringify(this.packagingInfo));
        this.settingsDialog.settingsDialogShow = true;
      },
      submitEdit() {
        const { name, domain, company, packageName } = JSON.parse(
          this.form.appItemInfo
        );
        const { primaryDomainUrl, gitUrl, gitBranch } = this.settingsDialog.form;
        const params = {
          primaryDomainUrl,
          gitUrl,
          gitBranch,
          operator: this.user.username,
          appName: name,
          domain,
          company,
          appPackage: packageName
        };
        this.$api.systemManage.addapppackconfig(params).then(res => {
          const { status, data, error } = res;
          if ('1' === status && error === '00000000') {
            this.$message.success(this.$t('common.successfulOperation'));
            this.getPackagingInfo();
            this.settingsDialog.settingsDialogShow = false;
          }
        });
      },
      //初始化自动发送短信
      initSmsTemplateForAppName() {
        this.$confirm(
          this.$t('common.confirmOneClickInitialization'),
          this.$t('salesManage.tips'),
          {
            confirmButtonText: this.$t('common.confirmOk'),
            cancelButtonText: this.$t('common.cancel'),
            type: 'warning'
          }
        )
          .then(() => {
            const { name, domain, company } = JSON.parse(this.form.appItemInfo);
            const params = {
              appName: name,
              domain,
              company,
              operatorId:  this.user.id,
              operatorName: this.user.username
            };
            this.$api.sms.initSmsTemplateForAppName(params).then(res => {
              const { status, data, error } = res;
              if ('1' === status && error === '00000000') {
                this.$message.success(this.$t('common.successfulOperation'));
                this.querySmsUpdateTime();
              }
            });
          })
          .catch(() => {

          });
      },
      //初始化催收阶段和短信
      initConfigAndTemplateForAppName() {
        this.$confirm(
          this.$t('common.confirmOneClickInitialization'),
          this.$t('salesManage.tips'),
          {
            confirmButtonText: this.$t('common.confirmOk'),
            cancelButtonText: this.$t('common.cancel'),
            type: 'warning'
          }
        )
          .then(() => {
            const { name, domain, company } = JSON.parse(this.form.appItemInfo);
            const params = {
              appName: name,
              domain,
              company
            };
            this.$api.collection.initConfigAndTemplateForAppName(params).then(res => {
              const { status, data, error } = res;
              if ('1' === status && error === '00000000') {
                this.$message.success(this.$t('common.successfulOperation'));
                this.queryCollectionUpdateTime();
              }
            });
          })
          .catch(() => {

          });
      },
      //查询短信初始化更新时间
      querySmsUpdateTime() {
        const { name, domain, company } = JSON.parse(this.form.appItemInfo);
        const params = {
          appName: name,
          domain,
          company
        };
        this.$api.sms.queryLately(params).then(res => {
          const { status, data, error } = res;
          if ('1' === status && error === '00000000' && data) {
            this.initialUpTimes.smsUpdateTime = data.updateTime;
          }else {
            this.initialUpTimes.smsUpdateTime = ''
          }
        });
      },
      queryCollectionUpdateTime() {
        const { name, domain, company } = JSON.parse(this.form.appItemInfo);
        const params = {
          appName: name,
          domain,
          company
        };
        this.$api.collection.querylately(params).then(res => {
          const { status, data, error } = res;
          if ('1' === status && error === '00000000' && data) {
            this.initialUpTimes.collectionUpdateTime = data.updateTime;
          }else {
            this.initialUpTimes.collectionUpdateTime = ''
          }
        });
      }
    },
    created() {
      that = this;
      this.getAppList();
    },
    filters: {
      substrText(val, num) {
        if (val && val.length > num) {
          return val.substr(0, num) + '...';
        } else {
          return val;
        }
      }
    }
  };
</script>

<style lang="scss">
  [data-page='systemAuthority-appInitialConfiguration'] {
    .el-col {
      padding-left: 10px;
    }
    .table_list {
      table.gridtable {
        width: 100%;
        font-size: 14px;
        color: #606266;
        border-width: 1px;
        word-break:break-all;
        white-space:pre-wrap;
        text-align: center;
        tr {
          th {
          width: 25%;
          border-width: 1px;
          padding: 15px 10px;
          border-color: #303333;
          font-size: 14px;
          font-weight: bold;
          background-color: #f0f4f5;
          border-bottom: 1px solid #ebeef5;
        }
        td {
          width: 25%;
          border-width: 1px;
          padding: 15px 10px;
          border-color: #666666;
          background-color: #ffffff;
          border-bottom: 1px solid #ebeef5;
        }
        }
      }
    }
  }
</style>
